package _17_剑指Offer;

import _17_剑指Offer.datastrcute.TreeNode;

public class _37_剑指Offer序列化二叉树 {

    private static final String EMPTY = "#";

    private static final String SPLIT = "!";


    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        preTraverse(root, sb);
        return sb.toString();
    }

    private void preTraverse(TreeNode root, StringBuilder sb) {
        if (root == null) {
            sb.append(EMPTY).append(SPLIT);
            return;
        }

        sb.append(root.val).append(SPLIT);
        preTraverse(root.left, sb);
        preTraverse(root.right, sb);
    }

    private int index;

    // 1!2!#!#!3!4!#!#!5!#!#!
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        return deserialize(data.split(SPLIT));
    }

    public TreeNode deserialize(String[] split) {
        String value = split[index++];
        if (EMPTY.equals(value)) {
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(value));

        root.left = deserialize(split);

        root.right = deserialize(split);
        return root;
    }

}
